package com.mediacloud.app.newsmodule.fragment.newslist;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.View;

import com.eventTrack.TXReportManager;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.assembly.widget.EmbedRecyclerView;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.ViewUtils;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.fragment.BaseNewsListFragmentX;
import com.mediacloud.app.newsmodule.fragment.ExtendKt;
import com.mediacloud.app.newsmodule.fragment.ListPreLoadTool;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.UniqueUtils;
import com.mediacloud.app.user.model.UserInfo;
import com.ty.sdk.Ty;
import com.utils.DeviceUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wzw on 2023/4/19 10:11
 * desc：
 */
public class TXRecommendFragment extends BaseNewsListFragmentX {

    public UserInfo userInfo;
    public String uuid;
    public String uuidTx;
    public List<ArticleItem> articleListTop = new ArrayList<>();
    // public List<ArticleItem> articleListBody = new ArrayList<>();
    public int pageNum = 1;
    public boolean isLoading = false;
    public RecommendRvAdapter recommendRvAdapter;
    public EmbedRecyclerView rvTop;
    public View viewTop;

    @Override
    public void initView() {
        super.initView();
        userInfo = UserInfo.getUserInfo(getActivity());
        uuid = DeviceUtils.getUuid(getContext(), false);
        uuidTx = StringUtils.getClient();
        mArticleListData = new ArticleListData();
        viewTop = LayoutInflater.from(getActivity()).inflate(R.layout.rv_top_recommend, null, false);
        rvTop = viewTop.findViewById(R.id.rv_recommend_top);
        rvTop.setLayoutManager(ViewUtils.generateRecyclerLinearLayoutManager(getActivity(), true));
        recommendRvAdapter = new RecommendRvAdapter(R.layout.item_top_recommend);
        rvTop.setAdapter(recommendRvAdapter);
        mCatalogContentItemListView.addHeaderView(viewTop);
        recommendRvAdapter.setOnItemClickListener((adapter, view, position) -> {
            ArticleItem item = (ArticleItem) adapter.getItem(position);
            assert item != null;
            TXReportManager.getInstance().app_jhapp_rec_content_click(null, null, item.getId() + "", TXReportManager.getInstance().getContentShowType(item.getType()));
            NewsItemClickUtils.OpenItemNewsHandle(getContext(), item.getType(), item, new CatalogItem());
        });
    }

 /*   @Override
    public void choosed() {
        super.choosed();
        f5();
    }*/

    @SuppressLint("MissingSuperCall")
    @Override
    public void doRefresh() {
        preLoadKit.onRefresh();
        ExtendKt.getRefreshData(this, null);
    }

    @Override
    public void toPreload(int preNum) {
        ExtendKt.preloadIntelligentRecommend(this, preNum);
    }
    private int noMore=0;
    @Override
    public void setData(ArticleListData result) {
       // mArticleListData.model_id = result.model_id;
       // mArticleListData.request_id = result.request_id;
        /*if (preLoadKit.getPageNum() == 1 && !preLoadKit.getHasMore() && result.articleList != null && result.articleList.size() == 0) {
            ArticleItem footerEmptyArticleItem = new ArticleItem();
            footerEmptyArticleItem.setType(TypeX.CUSTOM.Footer_Empty);
            result.articleList.add(footerEmptyArticleItem);
            isAddFooterEmptyArticleItem = true;
        }*/

        if (adaptor == null) return;
        isLoading = false;

        mXSmartRefreshLayout.finishLoadMore();

        ListPreLoadTool.preLoad(requireContext(), result.articleList);
        if (adaptor.getListContentData() == null) {
            adaptor.setListContentData(UniqueUtils.removeDuplicates(result.articleList, null));
        } else {
            List<ArticleItem> listContentData = adaptor.getListContentData();
            for (int i = 0; i < listContentData.size(); i++) {
                if (listContentData.get(i).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH) {
                    listContentData.remove(i);
                    break;
                }
            }
            int oldSize = listContentData.size();
            List<ArticleItem> articleListUnique = preLoadKit.getPageNum() != 1 ? UniqueUtils.removeDuplicates(listContentData, result.articleList) : UniqueUtils.removeDuplicates(result.articleList, listContentData);
            boolean noNew= oldSize >= articleListUnique.size();
            if (noNew) {
                // preLoadKit.setHasMore(false);
                noMore++;
            }else{
                noMore=0;
            }
            if (noMore>2){
                preLoadKit.setHasMore(false);
            }
            if (preLoadKit.getPageNum() == 1) {
                //去重数据集合减去原本数据就是推荐的新数据
                mXSmartRefreshLayout.setHeaderText("智能引擎为您发现" + (articleListUnique.size() - oldSize) + "条内容");
                if (!noNew){
                    //下拉刷新时最多显示200条数据
                    if (articleListUnique.size() < 200) {
                        adaptor.setListData(articleListUnique);
                    } else if (articleListUnique.size() >= 200) {
                        adaptor.setListData(articleListUnique.subList(0, 200));
                    }
                    if (adaptor.getListContentData().size() > 0 && oldSize != 0) {
                        ArticleItem articleItem = new ArticleItem();
                        articleItem.setType(TypeX.CUSTOM.SMART_RECOMMENT_REFRESH);
                        adaptor.getListContentData().add(oldSize, articleItem);
                    }
                }


//                if (listContentData.get(listContentData.size() - 1).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH || listContentData.get(0).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH || listContentData.get(articleListTop.size()).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH) {
//                    adaptor.getListContentData().remove(listContentData.size() - 1);
//                }
//                if(NetWorkUtil.IsNetWorkEnable(getActivity())){
//                    MMKV.mmkvWithID(XKey.RECOMMEND_REFRESH_DATA).remove(catalogID);
//                    String toJson = new Gson().toJson(adaptor.getListContentData());
//                    MMKV.mmkvWithID(XKey.RECOMMEND_REFRESH_DATA).putString(catalogID, toJson);
//                }
            } else {
                if (!noNew){
                    adaptor.setListData(articleListUnique);
                }

            }

        }
        /*List<ArticleItem> listContentData = adaptor.getListContentData();
        if (listContentData.get(listContentData.size() - 1).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH
                || listContentData.get(0).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH
                || listContentData.get(articleListTop.size()).getType() == TypeX.CUSTOM.SMART_RECOMMENT_REFRESH) {
            adaptor.getListContentData().remove(listContentData.size() - 1);
        }*/

        mArticleListData.articleList=adaptor.getListContentData();
        adaptor.notifyDataSetChanged();
        showNoDataView();

        dataReady = true;
        if (preLoadKit.getPageNum() == 1) {

           // if (hadChoosed) {
                app_jhapp_home_subtab_content_imp();
           // }
        }
    }

    void showNoDataView() {
        mXSmartRefreshLayout.setNoMoreData(adaptor.getListContentData() == null || adaptor.getListContentData().size() == 0);
    }
//    @Override
//    public void initToRefresh() {
//        if(!NetWorkUtil.IsNetWorkEnable(getActivity())){
//            useCache();
//        }
//    }
//
//    private void useCache() {
//        String refreshData = MMKV.mmkvWithID(XKey.RECOMMEND_REFRESH_DATA).getString(catalogID, null);
//        if (!TextUtils.isEmpty(refreshData)) {
//            try {
//                ArticleListData articleListData = new ArticleListData();
//                List<ArticleItem> articleItem = JSON.parseArray(refreshData, ArticleItem.class);
//                preLoadKit.setHasMore(true);
//                articleListData.articleList = articleItem;
//                preLoadKit.getPreLoadData().add(articleListData);
//                showStateView(TYPE_LOADING, false);
//                setData(articleListData);
//                preLoadKit.preload();
//            } catch (Exception e) {
//                e.printStackTrace();
//                innerUserCache();
//            }
//
//        } else {
//            innerUserCache();
//        }
//    }
//
//    private void innerUserCache() {
//        String refreshData = MMKV.mmkvWithID(XKey.RECOMMEND_REFRESH_DATA).getString(catalogID, null);
//        if (adaptor != null && !TextUtils.isEmpty(refreshData)) {
//            ArticleListData articleListData = new ArticleListData();
//            List<ArticleItem>  articleItem = JSON.parseArray(refreshData, ArticleItem.class);
//            showStateView(TYPE_LOADING, false);
//            articleListData.articleList = articleItem;
//            setData(articleListData);
//        } else {
//            showStateView(TYPE_LOADING, false);
//            preLoadKit.onRefresh();
//            doRefresh();
//        }
//    }
}
